import numpy as np
import cv2
import os

# 需要读取的图像路径
IMAGE_PATH = 'C:\\Users\\duanchen\\Documents\\Tencent Files\\1832931759\\FileRecv\\images\\duanchen'

# 让OpenCV使用人脸识别分类器
classfier = cv2.CascadeClassifier("D:\\opencv\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_alt2.xml")


# 将该路径下的图片全部转换成灰度图像
imgs = []


# 该函数可以将人脸照片不必要的部分剔除，从而减少工作量
def read_path(file_pathname):
    # 遍历该目录下的所有图片文件
    num = 0
    for filename in os.listdir(file_pathname):
        img = cv2.imread(file_pathname + '/' + filename)
        # 下面第一行是将RGB转成单通道灰度图
        grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 将位置信息储存起来
        faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
        if len(faceRects) > 0:  # 大于0则检测到人脸
            for faceRect in faceRects:  # 单独框出每一张人脸
                x, y, w, h = faceRect

                # 将当前帧保存为图片
                img_name = '{}.jpg'.format(num)
                num = num + 1
                image = grey[y - 10: y + h + 10, x - 10: x + w + 10]
                cv2.imwrite(file_pathname+"/"+img_name, image)
        imgs.append(image.shape)


read_path(IMAGE_PATH)
imgs = np.array(imgs)
print(imgs)